﻿namespace Utility1
{
    using Microsoft.Win32;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Net;
    using System.Net.Mail;
    using System.Reflection;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Xml;

    public static class WebUtils
    {
        private static Dictionary<string, string> knownMimes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    

        static WebUtils()
        {
            knownMimes.Add(".jpg", "image/pjpeg");
            knownMimes.Add(".png", "image/x-png");
            knownMimes.Add(".gif", "image/gif");
            knownMimes.Add(".ico", "image/x-icon");
            knownMimes.Add(".bmp", "image/bmp");
            knownMimes.Add(".wmv", "video/x-ms-wmv");
        }

        public static string GetBaseUrl()
        {
            return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
        }

        public static string SystemUrl()
        {
           // return "http://localhost:1791";
           // return "http://msmart.vn";
            return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
        }

        public static string GetCookie(UserControl control, string key)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[GetUniqueKey(control)];
            if (null != cookie)
            {
                return cookie[key];
            }
            return null;
        }

        public static string GetFileExtension(string fileName)
        {
            string str = string.Empty;
            if (Path.GetExtension(fileName).ToUpper() == ".EXE")
            {
                return string.Empty;
            }
            int num = fileName.LastIndexOf('.');
            if ((num + 1) > 1)
            {
                str = fileName.Substring(num + 1);
            }
            return str;
        }

        public static string GetFileImageExtension(string fileName)
        {
            string str = string.Empty;
            string extension = Path.GetExtension(fileName);
            if (((extension.ToUpper() == ".JPG") || (extension.ToUpper() == ".GIF")) || (extension.ToUpper() == ".PNG"))
            {
                int num = fileName.LastIndexOf('.');
                if ((num + 1) > 1)
                {
                    str = fileName.Substring(num + 1);
                }
            }
            return str;
        }

        public static string GetFileName(string fileName)
        {
            if (fileName == string.Empty)
            {
                return string.Empty;
            }
            if (Path.GetFileNameWithoutExtension(fileName).ToUpper() == ".EXE")
            {
                return string.Empty;
            }
            return Path.GetFileName(fileName);
        }

        public static string GetHostPath()
        {
            string absoluteUri = HttpContext.Current.Request.Url.AbsoluteUri;
            int length = absoluteUri.LastIndexOf('/');
            absoluteUri = absoluteUri.Substring(0, length);
            length = absoluteUri.LastIndexOf('/');
            return absoluteUri.Substring(0, length);
        }

        public static string GetInfoFileName(string fileName)
        {
            if (fileName == string.Empty)
            {
                return string.Empty;
            }
            return Path.GetFileNameWithoutExtension(fileName);
        }

        public static string GetKnownMime(string filespec)
        {
            string extension = Path.GetExtension(filespec);
            if (knownMimes.ContainsKey(extension))
            {
                return knownMimes[extension];
            }
            return null;
        }

        public static string GetMailTemplate(string filePath)
        {
            string str = string.Empty;
            if (!System.IO.File.Exists(filePath))
            {
                return str;
            }
            StreamReader reader = new StreamReader(filePath, Encoding.GetEncoding("UTF-8"));
            reader.BaseStream.Seek(0L, SeekOrigin.Begin);
            while (true)
            {
                string str2 = reader.ReadLine();
                if (str2 == null)
                {
                    reader.Close();
                    return str;
                }
                str = str + str2 + "\r\n";
            }
        }

        public static string GetMimeType(string fileName)
        {
            string str = "application/unknown";
            string name = Path.GetExtension(fileName).ToLower();
            RegistryKey key = Registry.ClassesRoot.OpenSubKey(name);
            if ((key != null) && (key.GetValue("Content Type") != null))
            {
                str = key.GetValue("Content Type").ToString();
            }
            return str;
        }

        public static string GetTitleFromParamPage(string pageParam)
        {
            string str = string.Empty;
            switch (pageParam)
            {
                case "newadmin":
                    return "New Admin";

                case "editadmin":
                    return "Admin Edit";

                case "editcompany":
                    return "Company Edit";

                case "newcompany":
                    return "New Company";

                case "newuser":
                    return "New Company User";

                case "addnewusercompany":
                    return "New Company User";

                case "edituser":
                    return "Company User Edit";

                case "accountuser":
                    return "Account";
            }
            return str;
        }

        public static string GetThemeConfigXmlFilespec(string theme)
        {
            return Path.Combine(GetThemesTemplatePath(theme), "config.xml");
        }

        public static string GetThemesTemplatePath(string theme)
        {
            return Path.Combine(GetThemesTemplateRoot(), theme);
        }

        public static string GetThemesTemplateRoot()
        {
            return (HttpContext.Current.Request.PhysicalApplicationPath + Path.Combine("App_Data", "Themes_Template"));
        }

        public static string GetUniqueKey(UserControl control)
        {
            if (null == control)
            {
                return HttpContext.Current.Request.FilePath;
            }
            return string.Format("{0}_{1}", HttpContext.Current.Request.FilePath, control.ClientID);
        }

        public static string GetUrlImage(string configAppSetting, string fileName)
        {
            string baseUrl = GetBaseUrl();
            if (!string.IsNullOrEmpty(fileName))
            {
                string path = Path.Combine(ConfigurationManager.AppSettings[configAppSetting], fileName);
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(path)))
                {
                    return Utils.CombineUrl(baseUrl, path);
                }
                return Utils.CombineUrl(baseUrl, ConfigurationManager.AppSettings["SrcNoImage"]);
            }
            return Path.Combine(baseUrl, ConfigurationManager.AppSettings["SrcNoImage"]);
        }

        public static string GetUrlImage(string configAppSetting, string fileName, string fileReplaceIfNotLoad)
        {
            string baseUrl = GetBaseUrl();
            if (!string.IsNullOrEmpty(fileName))
            {
                string path = Path.Combine(ConfigurationManager.AppSettings[configAppSetting], fileName);
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(path)))
                {
                    return Utils.CombineUrl(baseUrl, path);
                }
                return GetUrlImage(configAppSetting, fileReplaceIfNotLoad);
            }
            return GetUrlImage(configAppSetting, fileReplaceIfNotLoad);
        }

        public static string GetWebPath()
        {
            string absoluteUri = HttpContext.Current.Request.Url.AbsoluteUri;
            int length = absoluteUri.LastIndexOf('/');
            return absoluteUri.Substring(0, length);
        }

        public static void IncludeCSS(Page page, string cssfile)
        {
            HtmlGenericControl child = new HtmlGenericControl("link");
            child.Attributes.Add("rel", "stylesheet");
            child.Attributes.Add("type", "text/css");
            child.Attributes.Add("href", cssfile);
            page.Header.Controls.Add(child);
        }

        public static void IncludeJS(Page page, string jsfile)
        {
            HtmlGenericControl child = new HtmlGenericControl("script");
            child.Attributes.Add("type", "text/javascript");
            child.Attributes.Add("src", jsfile);
            page.Header.Controls.Add(child);
        }

        public static bool IsCurrentPage(string pageUrl)
        {
            return HttpContext.Current.Request.Url.AbsoluteUri.StartsWith(pageUrl, StringComparison.OrdinalIgnoreCase);
        }

        public static XmlDocument LoadThemeConfigXml(string theme)
        {
            XmlDocument document = new XmlDocument();
            document.Load(GetThemeConfigXmlFilespec(theme));
            return document;
        }

        public static void Redirect301(string url)
        {
            HttpContext.Current.Response.Status = "301 Moved Permanently";
            HttpContext.Current.Response.AddHeader("Location", url);
            HttpContext.Current.Response.End();
        }

        public static void ReloadPage()
        {
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl, true);
        }

        private static string RenderControl(Control control)
        {
            StringBuilder sb = new StringBuilder();
            using (StringWriter writer = new StringWriter(sb))
            {
                using (HtmlTextWriter writer2 = new HtmlTextWriter(writer))
                {
                    control.RenderControl(writer2);
                }
            }
            return sb.ToString();
        }

        public static string RenderControl(string path, string propertyName, object propertyValue)
        {
            Page handler = new Page();
            UserControl control = (UserControl) handler.LoadControl(path);
            if (null != propertyValue)
            {
                PropertyInfo property = control.GetType().GetProperty(propertyName);
                if (null == property)
                {
                    throw new ApplicationException(string.Format("Control {0} does not have {1} property", path, propertyValue));
                }
                property.SetValue(control, propertyValue, null);
            }
            handler.Controls.Add(control);
            StringWriter writer = new StringWriter();
            HttpContext.Current.Server.Execute(handler, writer, false);
            return writer.ToString();
        }

        public static void SendEmail(string subject, string from, string to, string header, string body)
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]) {
                Credentials = new NetworkCredential(ConfigurationManager.AppSettings["UserMail"], ConfigurationManager.AppSettings["PassMail"])
            };
            message.From = new MailAddress(from);
            message.To.Add(to);
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = body;
            message.BodyEncoding = Encoding.UTF8;
            message.Headers.Add("X-Company", "vivaland.vn");
            message.Headers.Add("X-Location", "Vietnamese");
            try
            {
                client.Send(message);
            }
            catch (Exception)
            {
            }
        }

        public static string SetBuild(string url)
        {
            return (GetWebPath() + "/" + url);
        }

        public static void SetCookie(UserControl control, string key, string value)
        {
            HttpContext.Current.Response.Cookies[GetUniqueKey(control)][key] = value;
        }
    }
}

